<template>
  <div class="embedded-docs">
    <iframe :src="iframeSrc" frameborder="0" width="100%" height="800" style="border: 1px solid #ddd" @load="onIframeLoad"></iframe>
  </div>
</template>

<script lang="ts" name="modelcomponents-modelComponents" setup>
  import { ref, computed, onMounted } from 'vue';
  import { useRoute } from 'vue-router';

  const route = useRoute();
  const selectedId = ref<string | null>(null);

  const iframeSrc = computed(() => {
    const baseUrl = 'http://api.fuxicloud.com:9810/docs/';
    if (selectedId.value) {
      return `${baseUrl}?id=${selectedId.value}`;
    }
    return baseUrl;
  });

  const onIframeLoad = () => {
    console.log('Iframe loaded successfully');
  };

  const updateSelectedId = (id: string) => {
    selectedId.value = id;
  };

  onMounted(() => {
    if (route.query.id) {
      selectedId.value = route.query.id as string;
    }
  });

  const sendMessageToIframe = (message: any) => {
    const iframe = document.querySelector('iframe');
    if (iframe && iframe.contentWindow) {
      iframe.contentWindow.postMessage(message, 'http://api.fuxicloud.com:9810');
    }
  };

  onMounted(() => {
    window.addEventListener('message', (event) => {
      if (event.origin !== 'http://api.fuxicloud.com:9810') return;

      console.log('Received message from iframe:', event.data);
    });
  });

  defineExpose({
    updateSelectedId,
    sendMessageToIframe,
  });
</script>

<style scoped>
  .embedded-docs {
    width: 100%;
    height: 100%;
  }

  .embedded-docs iframe {
    width: 100%;
    height: calc(100vh - 100px);
    min-height: 600px;
  }
</style>
